var path = require('path'),
  fs = require('fs'),
  DC = require('./old/full-citys');

function log(msg) {
  console.log(msg);
}

function write_file(fullname, data) {
  fs.writeFile(fullname, typeof data == 'string' ? data : JSON.stringify(data), 'utf-8', function (err) {
    if (err) return log('写入文件失败: ' + fullname + '   =>   ' + err.message);
    log('写入文件成功: ' + fullname);
  });
}

function format_prov_name(name) {
  name = name.trim().replace('特别行政区', '').replace(/(维吾尔|回族|壮族)?自治区$/, '');
  switch (name) {
    case '宁夏':
    case '广西':
      return name + '省';
  }

  return name;
}

function format_city_name(name) {
  name = name.trim().replace('特别行政区', '').replace(/(藏族|蒙古族|回族|苗族|壮族|土家族|布依族|侗族|彝族|羌族|白族|黎族|哈尼族|傈僳族|傣族|景颇族|朝鲜族|哈萨克|苏柯尔克孜)/g, '').replace(/自治(州|县)$/, '$1');
  if (name.length > 3) name = name.replace(/蒙古|林区$/, '');
  return name;
}

var map_keep_raw_name = {
  'CN101131308': true,   //新疆和田地区和田市
  'CN101131309': true,   //新疆和田地区和田县
  'CN101131410': true,   //新疆阿勒泰地区阿勒泰
  'CN101150607': true,   //青海玉树州玉树
  'CN101201009': true,   //湖北恩施州恩施
  'CN101290213': true,   //云南大理州大理
  'CN101290811': true,   //云南楚雄州楚雄
  'CN101290609': true    //云南文山州文山
};

var map_city_by_fullname_cn = {}, map_city_by_fullname_en = {};

function parse_txt(texts) {
  var list_full = [],
    list_prov = [],
    map_prov = {},

    list_city_array = [],
    map_city_cn = {},

    list_duplicate_city_name = [],
    map_duplicate_city_name = {},

    list_duplicate_city_name_log = [];

  (texts || '').split('\n').forEach(function (text, i) {
    text = text.trim();
    if (!text || text.startsWith('//') || i < 2) return;

    var vs = text.split(/,/),
      code = vs[0],                //城市/地区编码
      city_en = vs[1],             //英文名称
      city_cn = vs[2],             //中文名称
      country_code = vs[3],        //国家代码
      country_en = vs[4],          //国家英文名称
      country_cn = vs[5],          //国家中文名称
      prov_en = vs[6],             //省英文名称
      prov_cn = vs[7],             //省中文名称
      parent_city_en = vs[8],      //所属上级市英文名称
      parent_city_cn = vs[9],      //所属上级市中文名称
      timezone = vs[10],           //时区
      lat = vs[11],                //纬度
      lon = vs[12];                //经度

    if (!code || !city_cn || !prov_cn || !parent_city_cn) return;

    if (code.startsWith('101') && code.length == 9) code = 'CN' + code;

    var fullname_cn = prov_cn + '_' + parent_city_cn + '_' + city_cn;
    if (!map_keep_raw_name[code]) {
      var last_cn_code = map_city_by_fullname_cn[fullname_cn];
      if (last_cn_code) log('中文名称重复: ' + code + ' | ' + last_cn_code + ' => ' + fullname_cn);
      // return;
    }
    map_city_by_fullname_cn[fullname_cn] = code;

    var fullname_en = prov_en + '_' + parent_city_en + '_' + city_en;
    var last_en_code = map_city_by_fullname_en[fullname_en];
    if (last_en_code) {
      log('英文名称重复: ' + code + ' | ' + last_en_code + ' => ' + fullname_en);
      // return;
    }
    map_city_by_fullname_en[fullname_en] = code;

    prov_cn = format_prov_name(prov_cn);
    city_cn = format_city_name(city_cn);
    parent_city_cn = format_city_name(parent_city_cn);

    if (!map_keep_raw_name[code]) {
      var f_city_cn = city_cn.length > 2 ? city_cn.replace(/市$/, '') : city_cn,
        f_parent_city_cn = parent_city_cn.length > 2 ? parent_city_cn.replace(/市$/, '') : parent_city_cn;

      if (f_city_cn == f_parent_city_cn) city_cn = parent_city_cn;
    }

    var data = {
      code: code,
      en: city_en,
      cn: city_cn,
      country_code: country_code,
      country_en: country_en,
      country_cn: country_cn,
      prov_en: prov_en,
      prov_cn: prov_cn,
      pcity_en: parent_city_en,
      pcity_cn: parent_city_cn,
      timezone: timezone,
      lon: lon,
      lat: lat
    };

    var prov_cn_key = prov_cn.replace(/(省|市|区)$/, '');

    if (!map_prov[prov_cn_key]) {
      list_prov.push(prov_cn_key);
      map_prov[prov_cn_key] = prov_cn;
    }

    //list_city_array.push([code, city_cn, parent_city_cn != city_cn ? parent_city_cn : '', prov_cn != parent_city_cn ? prov_cn : '']);

    var list_city = map_city_cn[city_cn];
    if (!list_city) map_city_cn[city_cn] = list_city = [];
    list_city.push(data);

    if (list_city.length > 1 && !map_duplicate_city_name[city_cn]) {
      list_duplicate_city_name.push(city_cn);
      map_duplicate_city_name[city_cn] = true;
    }

    list_full.push(data);
  });

  log('\n');

  list_duplicate_city_name.forEach(function (city_cn) {
    var list_city = map_city_cn[city_cn];
    if (!list_city || list_city.length <= 1) return;

    var text = list_city.map(function (data) {
      return data.prov_cn + data.pcity_cn + data.cn + ' - ' + data.code;
    }).join(' | ');

    list_duplicate_city_name_log.push(text);

    log('城市名称重复: ' + text);
  });

  var list = [], map_subs = {};

  list_full.forEach(function (data) {
    var ps = map_city_cn[data.pcity_cn] || [], pdata;
    if (ps.length <= 0) {
      log('无父级城市数据: ' + data.code + '  |  ' + data.cn);
      return;
    }

    if (ps.length == 1) {
      pdata = ps[0];
    } else {
      ps.forEach(function (_data) {
        if (_data.prov_cn == data.prov_cn) {
          pdata = _data;
          return false;
        }
      });
      //log(data.cn + '  =>  ' + pdata.prov_cn + pdata.pcity_cn + (pdata.cn != pdata.pcity_cn ? pdata.cn : ''));
    }

    if (!pdata) {
      log('无父级城市数据: ' + data.code + '  |  ' + data.cn);
      return;
    }

    var city = { code: data.code, cn: data.cn }, pcode = pdata.code;
    if (city.code == pcode && city.cn == pdata.cn) city.pcn = data.prov_cn;
    else city.pcode = pcode;

    var pkey = city.pcode || city.pcn;

    if (pkey) {
      var list_sub = map_subs[pkey];
      if (!list_sub) map_subs[pkey] = list_sub = [];

      list_sub.push([undefined, city.cn, city.code]);

      // if (city.code == 'CN101011500') {
      //   console.log('---------------------- ' + city.cn + ' -----------------------');
      //   console.log(pkey);
      //   console.log(list_sub);
      //   console.log('');
      // }
    }

    list_city_array.push([city.code, city.cn, pkey]);

    list.push(city);
  });

  log('\n');

  var my_provs = ['北京', '天津', '上海', '重庆', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '四川', '贵州', '云南', '西藏', '陕西', '甘肃', '青海', '宁夏', '新疆', '香港', '澳门', '台湾'],
    map_prov_id = {};

  my_provs.forEach(function (prov, i) {
    map_prov_id[prov] = i;
  });

  var dataAll = { countries: [[0, '中国']], '0': [] }, last_prov_id = my_provs.length - 1;

  list_prov.forEach(function (prov, i) {
    var prov_id = map_prov_id[prov];
    if (prov_id == undefined) prov_id = ++last_prov_id;

    var prov_cn = map_prov[prov] || prov;
    // dataAll['0'][prov_id] = [prov_id, prov_cn];
    dataAll['0'].push([prov_id, prov_cn]);

    var sub_citys = map_subs[prov_cn] || [];
    dataAll['0_' + prov_id] = sub_citys;

    var map_city_id = {},
      max_city_id = -1;

    //优先使用老数据中的city id
    sub_citys.forEach(function (c) {
      var dc = DC.getCityOrArea(c[2]);
      if (dc && dc.cid != undefined) {
        if (!map_city_id[dc.cid]) {
          map_city_id[dc.cid] = true;
          c[0] = dc.cid;
          if (dc.cid > max_city_id) max_city_id = dc.cid;
        }
      }
    });

    sub_citys.forEach(function (c) {
      if (c[0] == undefined) c[0] = ++max_city_id;

      var sub_areas = map_subs[c[2]];
      if (!sub_areas || sub_areas.length <= 0) {
        return log('无城区数据:' + JSON.stringify(c));
      }

      dataAll['0_' + prov_id + '_' + c[0]] = sub_areas;
    });

    sub_citys.sort(function (a, b) {
      return a[0] - b[0];
    });

    sub_citys.forEach(function (c) {
      var sub_areas = map_subs[c[2]];
      if (!sub_areas || sub_areas.length <= 0) return;

      var map_area_id = {},
        max_area_id = -1;

      sub_areas.forEach(function (c) {
        var dc = DC.getCityOrArea(c[2]);
        if (dc && dc.aid != undefined && dataAll['0_' + prov_id + '_' + dc.cid]) {
          if (!map_area_id[dc.aid]) {
            map_area_id[dc.aid] = true;
            c[0] = dc.aid;
            if (dc.aid > max_area_id) max_area_id = dc.aid;
          }
        }
      });

      sub_areas.forEach(function (c) {
        if (c[0] == undefined) c[0] = ++max_area_id;
      });

      sub_areas.sort(function (a, b) {
        return a[0] - b[0];
      });
    });
  });

  var dataOutput = {};
  dataOutput['countries'] = dataAll['countries'];
  dataOutput['0'] = dataAll['0'];

  //省份排序
  dataOutput['0'].sort(function (a, b) {
    var n = a[0] - b[0];
    return n == 0 ? 0 : (n > 0 ? 1 : -1);
  });

  //按省份、城市顺序组织数据
  dataOutput['0'].forEach(function (data) {
    var prov_id = data[0],
      citys_key = '0_' + prov_id,
      citys = dataAll[citys_key];

    if (!citys || citys.length <= 0) return;

    dataOutput[citys_key] = citys;
    citys.forEach(function (data) {
      var city_id = data[0],
        areas_key = citys_key + '_' + city_id,
        areas = dataAll[areas_key];

      dataOutput[areas_key] = areas;
    });
  });

  log('\n');

  //write_file('./data/citys.json', { provs: list_prov, citys: list_city_array });
  //write_file('./data/china-city-list.json', { provs: list_prov, citys: list });
  //write_file('./data/china-city-list.full.json', list_full);
  write_file('./data/full-citys.json', dataOutput);
  write_file('./重名地区.txt', list_duplicate_city_name_log.join('\n'))
}

function init() {
  var fullpath = path.resolve('./source/china-city-list.csv');
  if (!fs.existsSync(fullpath)) return log('文件不存在: ' + fullpath);

  fs.readFile(fullpath, function (err, data) {
    if (err) return log('读取文件错误: ' + err.message);

    parse_txt(data + '');
  });
}

init();